<template>
  <div class="role-layout">
    <div class="role-search">
      <Collapse>
        <Panel name="1">
          <Button type="primary" icon="ios-search">搜索</Button>
          <div slot="content" class="role-search-inp">
            <i-input v-model="searchData.name" placeholder="请输入角色名称" class="fl"></i-input>
            <Button type="primary" icon="ios-search" class="fl" @click="search"></Button>
          </div>
        </Panel>
      </Collapse>
    </div>
    <div class="role-table">
      <div class="role-table-title">
        <h2>系统设置<span>角色管理</span></h2>
        <div class="role-table-add">
          <Button type="primary" icon="edit" @click="addRole">新增角色</Button>
        </div>
      </div>
      <div class="role-table-main">
        <Table :columns="tableData" :data="roleTableData"></Table>
        <div class="role-table-page clearfix">
          <Page :total="totalNum" show-elevator show-total class="fr"></Page>
        </div>
      </div>
    </div>
    <!--角色弹窗-->
    <Modal class="edit-modal" v-model="roleModel.hidden" :title="roleModel.title" @on-ok="submitForm('ruleForm')"
           :mask-closable="false" :loading="roleModel.loading">
      <Form ref="ruleForm" :rules="rules" :model="ruleForm" :label-width="106">
        <Form-item prop="name" label="角色名称：">
          <i-input v-model="ruleForm.name" placeholder="请输入角色名称"></i-input>
        </Form-item>
        <Form-item prop="description" label="备注：">
          <i-input v-model="ruleForm.description" placeholder="请输入备注"></i-input>
        </Form-item>
      </Form>
    </Modal>
    <!--权限弹窗-->
    <Modal class="edit-modal" v-model="modalRoleObj.hidden" :title="modalRoleObj.title" @on-ok="roleListSubmit"
           @on-cancel="clearRoleList" :mask-closable="false" :loading="modalRoleObj.loading">
      <div v-for="(item, index) in checkData" :key="index">
        <i-button size="small">{{ item.moduleName }}</i-button>
        <Select v-model="item.checkVal" filterable multiple size="large">
          <Option v-for="check in item.moduleItems" :value="check.id" :key="index" :label="check.moduleName"></Option>
        </Select>
      </div>
    </Modal>
  </div>
</template>
<script type="text/ecmascript-6">
  import clearObj from '../../../utils/clearObj/index'
  import getRoleList from './js/getRoleList'
  import setRoleList from './js/setRoleList'

  export default {
    data () {
      return {
        companyId: JSON.parse(sessionStorage.getItem('companyId')),
        loginId: sessionStorage.getItem('loginId'),
        router: JSON.parse(sessionStorage.getItem('router')),
        searchData: {
          name: ''
        },
        tableData: [
          {title: '角色名称', key: 'name'},
          {title: '备注', key: 'description'},
          {title: '创建时间', key: 'createTime'},
          {
            title: '操作',
            key: 'action',
            width: 200,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.editRole(params.index)
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.getRole(params)
                    }
                  }
                }, '设置权限'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.remove(params.index)
                    }
                  }
                }, '删除')
              ])
            }
          }
        ],
        roleTableData: [],
        roleTableDataIndex: 0,
        roleTableRowData: {},
        totalNum: 0,
        // 修改或新增角色
        roleModel: {
          hidden: false,
          title: '',
          loading: true
        },
        ruleForm: {
          name: '', description: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入角色名称'}
          ],
          description: [
            {required: false, message: '请输入备注信息'}
          ]
        },
        // 设置角色权限
        modalRoleObj: {
          hidden: false,
          title: '设置权限',
          loading: true
        },
        // 路由参数
        checkData: []
      }
    },
    mounted () {
      // 第一步：获取角色信息
      this.getRoleData({params: {companyId: this.companyId}})
      // 第二步，写入权限列表
      this.setRoleInfo()
    },
    methods: {
      // 获取角色信息
      getRoleData (fromData) {
        let url = this.api.role.getRole
        this.$axios.get(url, fromData || {}).then((res) => {
          if (res.data.msg.code === '20000') {
            this.roleTableData = res.data.data
            this.totalNum = res.data.page.total
            console.log(res.data)
          } else if (res.data.msg.code === '40001') {
            this.$Message.error({content: res.data.msg.message, duration: 5})
            this.roleTableData = []
            this.totalNum = 0
          } else {
            this.$Message.error({content: res.data.msg.message, duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      search () { // 搜索
        this.getRoleData({
          params: {
            companyId: this.companyId,
            name: encodeURIComponent(this.searchData.name)
          }
        })
      },
      // 写入权限列表
      setRoleInfo () {
        for (let i = 0; i < this.router.length; i++) {
          this.router[i].checkVal = [] // 子级选择内容
        }
        this.checkData = this.router
      },
      // 编辑
      editRole (index) {
        this.roleModel.hidden = true
        this.roleModel.title = '编辑角色'
        this.roleTableDataIndex = index
        this.roleTableRowData = this.roleTableData[index]
        clearObj(this.ruleForm)
        let fromData = this.ruleForm
        fromData.name = this.roleTableData[index].name
        fromData.description = this.roleTableData[index].description
      },
      // 新增
      addRole () {
        this.roleModel.hidden = true
        this.roleModel.title = '新增角色'
        clearObj(this.ruleForm)
        this.$refs.ruleForm.resetFields()
      },
      // 删除
      remove (index) { // 删除
        console.log(index)
        console.log(this.roleTableData[index])
        let params = {
          roleId: this.roleTableData[index].id
        }
        this.del(params)
      },
      submitForm (name) { // 提交
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$Message.success('提交中。。。')
            if (this.roleModel.title === '编辑角色') {
              this.edit()
            } else {
              this.add()
            }
          } else {
            this.$Message.error('表单验证失败!')
            this.moduleQuit('roleModel')
          }
        })
      },
      add () { // 新增角色
        let url = this.api.role.add
        let formData = this.ruleForm
        let params = {
          companyId: this.companyId,
          creater: this.loginId,
          name: encodeURIComponent(formData.name),
          description: encodeURIComponent(formData.description)
        }
        this.$axios.get(url, {params: params}).then((res) => {
          console.log(res)
          if (res.data.msg.code === '20000') {
            let data = res.data.data
            let id = res.data.id
            res.data.data.id = id
            if (this.roleTableData.length < 10) {
              this.roleTableData.unshift(data)
            } else {
              this.roleTableData.splice(9, 1)
              this.roleTableData.unshift(data)
            }
            this.$Message.success('新增成功')
            this.roleModel.hidden = false
          } else {
            this.$Message.error(res.data.msg.message)
            this.moduleQuit('roleModel')
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error('网络异常')
        })
      },
      edit () { // 编辑角色
        let url = this.api.role.update
        let formData = this.ruleForm
        let params = {
          id: this.roleTableRowData.id,
          companyId: this.companyId,
          modifier: this.loginId,
          name: encodeURIComponent(formData.name),
          description: encodeURIComponent(formData.description)
        }
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            this.getRoleData()
            this.$Message.success('编辑成功')
            this.roleModel.hidden = false
          } else {
            this.$Message.error(res.data.msg.message)
            this.moduleQuit('roleModel')
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error('网络异常')
        })
      },
      del (params) { // 删除角色
        let url = this.api.role.delete
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            this.getRoleData()
            this.$Message.success('删除成功')
          } else {
            this.$Message.error(res.data.msg.message)
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error('网络异常')
        })
      },
      // 获取权限列表
      getRole (data) {
        console.log(data)
        this.roleTableRowData = data.row
        let url = this.api.role.getRoleList
        let params = {companyId: this.companyId, roleId: data.row.id}
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            let data = res.data.data
            getRoleList(data, this.checkData)
            this.modalRoleObj.hidden = true
            console.log(this.checkData)
          } else {
            this.$Message.error(res.data.msg.message)
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error('网络异常')
        })
      },
      roleListSubmit () {
        this.modalRoleObj.loading = true
        let url = this.api.role.updateRoleList
        let params = {}
        params.roleId = this.roleTableRowData.id
        params.moduleId = setRoleList(this.checkData)
        this.$axios.get(url, {
          params: {companyId: this.companyId, data: JSON.stringify(params)}
        }).then((res) => {
          console.log(res)
          if (res.data.msg.code === '20000') {
            this.$Message.success('修改权限成功')
            this.modalRoleObj.hidden = false
          } else {
            this.moduleQuit('modalRoleObj')
            this.$Message.success(res.data.msg.message)
          }
        }).catch((err) => {
          if (err) throw err
          this.moduleQuit('modalRoleObj')
        })
      },
      // 清空权限列表
      clearRoleList () {
        for (let i = 0; i < this.checkData.length; i++) {
          this.checkData[i].checkVal = [] // 子级选择内容
        }
      },
      // 阻止弹窗关闭
      moduleQuit (name) {
        this[name].loading = false
        setTimeout(() => {
          this[name].loading = true
        }, 1)
      }
    }
  }
</script>
